package edu.washington.cs.workflow.analysis.guistructure.uievents;

import org.uispec4j.Panel;
import org.uispec4j.PasswordField;
import org.uispec4j.UIComponent;

import edu.washington.cs.workflow.analysis.guistructure.uievents.UIEvent.WINDOW;
import edu.washington.cs.workflow.util.Utils;

public class PasswordFieldEvent extends AbstractUIEvent  {

	private final PasswordField pwdField;
	private final UIAction action;
	private final String text;
	
	public PasswordFieldEvent(PasswordField field, Panel panel, UIAction action, String text) {
		Utils.checkNotNull(field);
		Utils.checkNotNull(panel);
		Utils.checkNotNull(action);
		Utils.checkNotNull(text);
		Utils.checkTrue(action.equals(UIAction.SetText), "illegal value: " + action);
		this.pwdField = field;
		this.setCurrentPanel(panel);
		this.action = action;
		this.text = text;
	}
	
	@Override
	public UIComponent getUIComponent() {
		return this.pwdField;
	}

	@Override
	public UIAction getAction() {
		return this.action;
	}
	
	public String getText() {
		return this.text;
	}

	@Override
	public String toString() {
		return this.action + " passwordfield: " + this.pwdField + ", with text: " + this.text;
	}
	
	@Override
	public String getDescription() {
		return this.action + " passwordfield: "
		    + this.getUIComponent().getAwtComponent().getClass() + " : " + this.pwdField.getName();
	}
	
	@Override
	protected WINDOW probeWindowInfoInternal() {
		return WINDOW.NONE;
	}

	@Override
	public boolean canFireEvent() {
		return this.pwdField.isEnabled().isTrue();
	}
	
	@Override
	protected UIEventOutcome fireEventInternal() {
		
		UIEventOutcome outcome = new UIEventOutcome();
		Throwable error = null;
		try {
			this.pwdField.setPassword(text);
		}  catch (Throwable e) {
			error = e;
		}
		
		if(error != null) {
		    outcome.setError(error);
		}
		outcome.currentPanelClosed(super.isCurrentPanelClosed());
		return outcome;
	}
}
